import { defineStore } from "pinia";

import { getMenuList } from "@/api/permission";
import { login } from "@/api/user";
import { TOKEN_NAME, user_info } from "@/config/global";
import { store, usePermissionStore } from "@/store";

const InitUserInfo = {
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore("user", {
  state: () => ({
    token: localStorage.getItem(TOKEN_NAME) , // 默认token不走权限
    userInfo: {
      username: undefined,
      name: undefined,
      ...InitUserInfo,
    },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
    token:(state) => {
      console.log(state,'!!!!!!!!!!');
      return state.token;
    },
  },
  actions: {
    async login(userInfo) {
      let that=this;
      const { tenantCode, username, password, smsCaptcha, rand } = userInfo;
      const data = await login({
        tenantCode: tenantCode.trim(),
        username: username.trim(),
        password,
        smsCaptcha: smsCaptcha.trim(),
        rand,
      }).then(e=>{
         if (e) {
          localStorage.setItem(TOKEN_NAME,e.data.token );
           localStorage.setItem(user_info,JSON.stringify(e.data.userInfor));
           localStorage.setItem("loginTime",e.data.userInfor.loginTime);
           return true;
         }
       }).catch(e=>{
          return false;
        });
      return data;
    },

    async getUserInfo() {
      const mockRemoteUserInfo = async (token: string) => {
        if (token === "main_token") {
          return {
            name: "td_main",
            roles: ["all"], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
          };
        }
        return {
          name: "td_dev",
          roles: ["UserIndex", "DashboardBase", "login"], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
        };
      };
      const res = (await getMenuList()).user;

      this.userInfo = res;
    },
    async logout() {
      localStorage.removeItem(TOKEN_NAME);
      this.userInfo = { ...InitUserInfo };
      this.removeToken();
      window.location.reload();
    },
    async removeToken() {
      this.token = "";
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
  },
});

export function getUserStore() {
  return useUserStore(store);
}
